package com.wzt.greenhousemobile;

import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.R.bool;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.wzt.greenhouse.model.*;

public class DPWebService {
    static final String serviceUrl = "http://192.168.1.244/DPWebservice/DPService.asmx";
    static HttpTransportSE ht = null;
    static Handler activityHandler = null;
    static final String webServiceNamesapce = "http://tempuri.org/";
    static String objPropertyName = "Table";
    static ArrayList<GreenhouseControl> ghList = new ArrayList<GreenhouseControl>(); 
    static private int ghIndex = 0;
    static final String GetMSubType = "sensor";
    static final String GetCtrlType = "controller";
 	private static Runnable initWebServiceRunnable = new Runnable(){
		@Override
		public void run(){
			String method = "GetDPList";
			SoapObject request = new SoapObject(webServiceNamesapce, method);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); 
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);
			//envelope.bodyOut = request;
			ht = new HttpTransportSE(serviceUrl);
			ht.debug = true;
			try
			{
				ht.call(null, envelope);
				SoapObject   soapObject = (SoapObject) envelope.getResponse();
                if(soapObject!=null){
                    GetDPList(soapObject);
                }
				Message message = new Message();   
				message.what = 1;   
				if(activityHandler!=null)
				{
					activityHandler.sendMessage(message);   
				}
			}
			catch(Exception e)
			{
				String msgString = e.getMessage();
				if(msgString != null)
					Log.i("GHMobile", msgString);
				Message message = new Message();   
				message.what = 2;   
				if(activityHandler!=null)
					activityHandler.sendMessage(message);   
			}
			
		}

		private void GetDPList(SoapObject soapObject) {
            for(int i=0;i<soapObject.getPropertyCount();i++)
            {
              try
              {
            	  SoapObject obj = (SoapObject)soapObject.getProperty(i);
            	  if(obj.getName() != objPropertyName)
            	  {
            		  if(obj.getPropertyCount()>0)
            		  {
            			  GetDPList(obj);
            		  }
            	  }             }
              catch(Exception e)
              {
            	  SoapPrimitive obj = (SoapPrimitive)soapObject.getProperty("dangername");
        		  String dangerid = soapObject.getProperty("dangerid").toString();
        		  String nameString = obj.toString();
        		  GreenhouseControl gh = new GreenhouseControl(nameString,dangerid);
        		  ghList.add(gh);
        		  break;
            	  
              }

 
            }
			
		}
	};

	private static Runnable selectGHThread = new Runnable(){
		@Override
		public void run(){
			int groupIndex = 1;
			String method = "GetDPSubListXML";
			GreenhouseControl gh = ghList.get(ghIndex);
			if(!gh.isInit())
			{
				SoapObject request = new SoapObject(webServiceNamesapce, method);
				request.addProperty("prev_id",gh.getDangerid());
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); 
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				ht = new HttpTransportSE(serviceUrl);
				ht.debug = true;
				try
				{
					ht.call(null, envelope);
					SoapObject   soapObject = (SoapObject) envelope.getResponse();
		            if(soapObject!=null){
		            	SoapObject ds = (SoapObject)soapObject.getProperty("ds");
		            	for (int i = 0; i < ds.getPropertyCount(); i++) {
							SoapObject tbObject = (SoapObject)ds.getProperty(i);
							String idObject = tbObject.getProperty("dangerid").toString();
							String nameObject = tbObject.getProperty("dangername").toString();
							String kindObject = tbObject.getProperty("kind").toString();
							
							if(kindObject.toString().equals("controller"))
							{
								ControlInfo info = gh.getControlInfoById(idObject);
								if(info == null)
								{
									info = new ControlInfo(nameObject,idObject);
									gh.AddControl(info);
								}
								
								String typeObject = tbObject.getProperty("machinetype").toString();
								String comnum = tbObject.getProperty("comnum").toString();
								String comstop = tbObject.getProperty("comstop").toString();
								String state = tbObject.getProperty("isopen").toString();
								info.setComnum(comnum);
								info.setComstop(comstop);
								
								if(typeObject.equals("WAN"))
								{
									String comdown = tbObject.getProperty("comdown").toString();
									info.setComdown(comdown);
									info.setType(2);
								}
								if(typeObject.equals("WJM"))
								{
									String comdown = tbObject.getProperty("comdown").toString();
									info.setComdown(comdown);
									info.setType(1);
									info.setImageGroup(Integer.toString(groupIndex));
									groupIndex++;
									if(groupIndex>6)
										groupIndex=1;
									
								}
								if(typeObject.equals("WIN"))
								{
									info.setType(3);
								}
								if(typeObject.equals("WAT"))
								{
									info.setType(5);
								}
								
								info.setState(state);
	
							}
							if(kindObject.equals("sensorbox"))
							{
								MonitorBox box = gh.getMonitorBoxById(idObject);
								if(box == null)
								{
									box = new MonitorBox(nameObject,idObject);
									if(!GetMonitorBoxInfo(box))
										return;
									gh.AddMonitorBox(box);
								}
							}
						}
						Message message = new Message();   
						message.what = 1;   
						if(activityHandler!=null)
						{
							activityHandler.sendMessage(message);   
						}
		            }
				}
				catch(Exception e)
				{
					String msgString = e.getMessage();
					if(msgString != null)
						Log.i("GHMobile", msgString);
					Message message = new Message();   
					message.what = 2;   
					if(activityHandler!=null)
					{
						activityHandler.sendMessage(message);   
					}
				}
			}
		}
	};

	static boolean GetMonitorBoxInfo(MonitorBox box) {
		try
		{
			String method = "GetSensorValueListXML";
			SoapObject request = new SoapObject(webServiceNamesapce, method);
			request.addProperty("dangerid",box.getId());
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); 
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);
			ht = new HttpTransportSE(serviceUrl);
			ht.debug = true;
			ht.call(null, envelope);
			SoapObject   soapObject = (SoapObject) envelope.getResponse();
			
	        if(soapObject!=null){
	        	SoapObject ds = (SoapObject)soapObject.getProperty("ds");
	        	for (int i = 0; i < ds.getPropertyCount(); i++) {
					SoapObject tbObject = (SoapObject)ds.getProperty(i);
					String id = tbObject.getProperty("dangerid").toString();
					String name = tbObject.getProperty("dangername").toString();
					String value = tbObject.getProperty("sensor_value").toString();
					if(value.length() > 5)
					{
						value = value.substring(0,5);
					}
					String type =  tbObject.getProperty("type").toString();
					MonitorInfo info = box.getMonitorInfoById(id);
					if(info == null)
					{
						info = new MonitorInfo(name, type,id);
						box.AddMonitor(info);
					}
					info.setValue(value);
	        	}
	        }
		}
		catch(Exception e)
		{
			Message message = new Message();   
			message.what = 2;   
			if(activityHandler!=null)
			{
				activityHandler.sendMessage(message);   
			}
			return false;
			
		}
		return true;
	}

 	private static Runnable sendControlCommad = new Runnable(){
		@Override
		public void run(){
			String method = "WriteConSensor";
			SoapObject request = new SoapObject(webServiceNamesapce, method);
			request.addProperty("dangerid",sendParams.getDangerid());
			request.addProperty("order_type",sendParams.getOrder_type());
			request.addProperty("num",sendParams.getNum());
			request.addProperty("c_status",sendParams.getC_status());
			request.addProperty("userid",sendParams.getUserid());
			
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); 
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);
			//envelope.bodyOut = request;
			ht = new HttpTransportSE(serviceUrl);
			ht.debug = true;
			try
			{
				ht.call(null, envelope);
				SoapObject   soapObject = (SoapObject) envelope.getResponse();
                if(soapObject!=null){
                }
			}
			catch(Exception e)
			{
				String msgString = e.getMessage();
				if(msgString != null)
					Log.i("GHMobile", msgString);
			}
			
		}
	};	
	static Boolean checkMonitorState()
	{
		boolean success = true;
		GreenhouseControl gh = ghList.get(ghIndex);
		for(int i=0 ; i<gh.getMonistorCount() ;i++)
		{
			MonitorBox box = gh.getMonitorBox(i);
			if(!GetMonitorBoxInfo(box))
			{
				success = false;
			}
		}
		return success;
	}
	
	static void initWebService()
	{
    	new Thread(initWebServiceRunnable).start();
		
	}
	
	static void selectGH(int index)
	{
		ghIndex = index;
    	new Thread(selectGHThread).start();
	}
	
	public static int getGhIndex() {
		return ghIndex;
	}
	
	static private WriteConSensorParams sendParams = null;
	static public void setControlCmd(WriteConSensorParams params)
	{
		sendParams = params;
    	new Thread(sendControlCommad).start();
	}

	static public ArrayList<ControlInfo> changeStateCtrlList = new ArrayList<ControlInfo>();
	public static boolean checkControllerState() {
		String method = "GetDPSubListByKindXML";
		GreenhouseControl gh = ghList.get(ghIndex);
		if(!gh.isInit())
		{
			SoapObject request = new SoapObject(webServiceNamesapce, method);
			request.addProperty("prev_id",gh.getDangerid());
			request.addProperty("kind","controller");
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); 
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);
			ht = new HttpTransportSE(serviceUrl);
			ht.debug = true;
			try
			{
				ht.call(null, envelope);
				SoapObject   soapObject = (SoapObject) envelope.getResponse();
	            if(soapObject!=null){
	            	SoapObject ds = (SoapObject)soapObject.getProperty("ds");
	            	for (int i = 0; i < ds.getPropertyCount(); i++) {
						SoapObject tbObject = (SoapObject)ds.getProperty(i);
						String idObject = tbObject.getProperty("dangerid").toString();
						String kindObject = tbObject.getProperty("kind").toString();
						
						if(kindObject.toString().equals("controller"))
						{
							ControlInfo info = gh.getControlInfoById(idObject);
							if(info == null)
							{
								continue;
							}
							                                                                                                                                                                                                                                              
							String state = tbObject.getProperty("isopen").toString();
							if(info.getState().equals(state))
							{
								continue;
							}
							info.setState(state);
							changeStateCtrlList.add(info);								
							
						}
					}
	            }
			}
			catch(Exception e)
			{
				String msgString = e.getMessage();
				if(msgString != null)
					Log.i("GHMobile", msgString);
				return false;
			}
		}
		return true;
	}
}
